package com.steve.summary.tcc;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: STEVE
 * @Description: TCC协调者
 * @since: 2025-05-23
 */
public class TccCoordinator {

    private final List<TccParticipant> participants = new ArrayList<>();
    private final TransactionLog transactionLog;

    public TccCoordinator(TransactionLog transactionLog) {
        this.transactionLog = transactionLog;
    }

    public void addParticipant(TccParticipant participant) {
        participants.add(participant);
    }

    public boolean execute(String txId, int amount) {
        // Phase 1: Try
        List<TccParticipant> preparedParticipants = new ArrayList<>();
        for (TccParticipant p : participants) {
            if (!p.tryExecute(txId, amount)) {
                cancelAll(txId, preparedParticipants);
                return false;
            }
            preparedParticipants.add(p);
        }
        // Phase 2: Confirm
        for (TccParticipant p : preparedParticipants) {
            if (!p.confirm(txId)) {
                // 记录异常，触发告警
                System.err.println("Confirm失败需人工干预: " + txId);
                return false;
            }
        }
        return true;
    }

    private void cancelAll(String txId, List<TccParticipant> participants) {
        participants.forEach(p -> {
            try {
                p.cancel(txId);
            } catch (Exception e) {
                // 记录日志，触发补偿任务
                System.err.println("Cancel执行异常: " + e.getMessage());
            }
        });
    }

}
